import base64
import datetime
from typing import List, Union, Literal
from pydantic import Field, BaseModel, root_validator
from package.fastapi.schema import Page, BatchId, Cron
from common.analyzer_common.scheme import Search


class EventTriggerCondition(BaseModel):
    """"""
    type: Literal['event_count'] = Field(..., title='事件计数类型')
    op: Literal['>', '<', '=', '>=', '<='] = Field(..., title='操作类型', description='大于小于等于等条件', example='=')
    count: int = Field(..., title='次数', example=1)
    level: int = Field(..., title='告警等级', example=1)

    class Config:
        use_enum_values = True


class DistinctTriggerCondition(EventTriggerCondition):
    type: Literal['distinct_count'] = Field(..., title='独立数')
    field: str = Field(..., title='字段', description='对比字段', example='score')


class MaxTriggerCondition(DistinctTriggerCondition):
    type: Literal['max'] = Field(..., title='最大值')


class MinTriggerCondition(DistinctTriggerCondition):
    type: Literal['min'] = Field(..., title='最小值')


class AvgTriggerCondition(DistinctTriggerCondition):
    type: Literal['avg'] = Field(..., title='平均值')


class SumTriggerCondition(DistinctTriggerCondition):
    type: Literal['sum'] = Field(..., title='总和')



class _AlertConfigure(BaseModel):
    group_by: List[str] = Field(None, title='分组字段')
    triggers: List[Union[EventTriggerCondition, DistinctTriggerCondition, MaxTriggerCondition, MinTriggerCondition,
                   AvgTriggerCondition, SumTriggerCondition]] = Field(..., title='触发器',
                                                                      example=[{'op': '>', 'count': 3, 'level': 1,
                                                                                'type': 'event_count'}])


class _Notify(BaseModel):
    type: str = Field(..., title='类型')
    notify_id: str = Field(..., title='通告ID')


class EditAlert(Cron):
    name: str = Field(None, title='名称')
    description: str = Field(None, title='描述')
    category: Literal['event_count', 'field_count', 'group_by'] = Field(None, title='告警类型')

    search: Search = Field(..., title='搜索条件')
    configure: _AlertConfigure = Field(..., title='告警配置')
    notify: List[_Notify] = Field(None, title='通告配置')


class CreateAlert(EditAlert):
    pass 


class AlertOut(CreateAlert):
    id: str = Field(..., title='ID')
    created_at: datetime.datetime = Field(None, title='')

    class Config:
        orm_mode = True
        json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp() * 1000)}


class PageAlerts(Page):
    """获取页码条目"""
    data: List[AlertOut] = Field(..., title='')
